import cloud from '@lafjs/cloud'
let data
let dbName = "web-home"
const db = cloud.database();

export default async function (ctx: FunctionContext) {
  data = { ...ctx.body.data }
  switch (ctx.body.type) {
    case "details":  //查询
      return Search()
      break;

    default: //新增
      return setFunc()
      break;
  }
}

async function setFunc() {
  const { total } = await db.collection(dbName).count();
  if (total) {
    return update()
  } else {
    return add()
  }
}

async function add() {
  await cloud.nw.db.add({
    dbName,
    dataJson: data,
    cancelAddTime: true
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function update() {
  let query = { ...data }
  delete query._id
  await cloud.nw.db.update({
    dbName,
    whereJson: {
      _id: data._id,
    },
    dataJson: query
  });
  return cloud.utils.requestReturn({ data: "" })
}


async function Search() {
  let { data } = await db.collection(dbName).get()
  return cloud.utils.requestReturn({ data: data[0] })
}